package panda.metainfo;

import static java.sql.Types.VARCHAR;
import static panda.metainfo.TableManager.MAXNAMESIZE;

import java.util.HashMap;
import java.util.Map;

import panda.query.struct.SemAttribute;
import panda.record.RecordFile;
import panda.record.Schema;
import panda.record.TableToken;
import panda.server.Panda;
import panda.transaction.Transaction;

public class IndexManager {
	private TableToken tt;
	private Map<String, Map<String, IndexToken>> cache;

	IndexManager(boolean isNew, TableManager tm, Transaction tx) {
		if (isNew) {
			Schema sch = new Schema();
			sch.addAttribute(new SemAttribute("indexname"), VARCHAR,
					MAXNAMESIZE);
			sch.addAttribute(new SemAttribute("tablename"), VARCHAR,
					MAXNAMESIZE);
			sch.addAttribute(new SemAttribute("fieldname"), VARCHAR,
					MAXNAMESIZE);
			tm.createTable("index", sch, tx);
		}
		tt = tm.getTableToken("index", tx);
		updateCache(tx);
	}

	public void createIndex(String idx, String tbl, String fld, Transaction tx) {
		RecordFile rf = new RecordFile(tt, tx);
		rf.insert();
		rf.setString("indexname", idx);
		rf.setString("tablename", tbl);
		rf.setString("fieldname", fld);
		rf.close();
		updateCache(tx);
	}
	
	public void deleteIndex(String idx, Transaction tx) {
		
		Panda.getFileManager().delete("leaf" + idx + ".bt");
		Panda.getFileManager().delete("dir" + idx + ".bt");
		
		RecordFile rf = new RecordFile(tt, tx);
		
		while (rf.next()) 
			if (rf.getString("indexname").equals(idx)) rf.delete();
		rf.close();
		
		updateCache(tx);
	}
	
	public Map<String, IndexToken> getIndexToken(String tbl, Transaction tx) {
		return cache.get(tbl);
	}

	public void updateCache(Transaction tx) {
		cache = new HashMap<String, Map<String,IndexToken>>();
		
		RecordFile rf = new RecordFile(tt, tx);
		while (rf.next()) {
			Map<String, IndexToken> current;
			String tbl = rf.getString("tablename");
			
			if ((current = cache.get(tbl)) == null) {
				current = new HashMap<String, IndexToken>();
				cache.put(tbl, current);
			}
			String idx = rf.getString("indexname");
			String fld = rf.getString("fieldname");
			IndexToken it = new IndexToken(idx, tbl, fld, tx);
			current.put(fld, it);
		}
		rf.close();
	}
}